﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using CommonPatterns;
using CommonPatterns.IoC;
using CommonPatterns.Screen;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using OCDP.Client;
using OCDP.Shell.ConfigAccess;
using CommonPatterns.DesignPatterns;

namespace OCDP.Shell
{
    public partial class App : Application
    {
        private IUnityContainer container;

        protected override void OnStartup(StartupEventArgs e)
        {
            // initialize IoC container
            container = new UnityContainer();

            // the boostrapper aims to populate de IoC container
            var boostrapper = container.Resolve<Bootstrapper>();

            // loading config files
            container.FindAndRegisterConfigurationSection<IScreenManagmentConfig, ScreenManagmentConfig>("Chrome.config");
            
            // registering modules
            boostrapper.RegisterModule<OCDPModule>();

            // starting services
            var servicesTostart = container.FindAllImplementation<IStartableService>();
            // first load all services and then start them
            servicesTostart.ToList().ForEach(item => item.Start());

            // initializing the chrome App
            var chrome = container.Resolve<Chrome>();
            
            // adding view in the menu
            chrome.LoadViewsInMenu<OCDPModule>();

            // display the Chrome
            chrome.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            container.ResolveAll<IStartableService>().ForEach(item => item.Stop());
            container.ResolveAll<IDisposable>().ForEach(item => item.Dispose());
            base.OnExit(e);
        }
    }
}
